package com.gl.blank.simplewebapp;

import java.io.IOException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A http servlet that gets activated with path "/servlet-answer". See web.xml
 * for details.
 * 
 */
public class HelloWorldServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private static final String USER_DATA = "userData";
    private static final String SERVLET_OUTPUT = "servletOutput";

    /**
     * Processes get response. Reads user session bean defined in the index.jsp
     * page. Stores output message in another session bean. Forwards the request
     * to servlet-answer.jsp
     */
    @Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
            throws ServletException, IOException
    {
        UserData userData = (UserData) request.getSession().getAttribute( USER_DATA );

        System.out.println( "Get: time: " + new Date() );
        System.out.println( "Get: userInput: " + userData );

        request.getSession().setAttribute( SERVLET_OUTPUT,
            "Hi from servlet. Your input: " + (userData != null ? userData.getUserInput() : null) );
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(
            "/servlet-answer.jsp" );
        dispatcher.forward( request, response );
    }
}
